package jp.sinya.temicontact.service;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;

import jp.sinya.temicontact.RemoteConnection;

/**
 * @author Koizumi Sinya
 * @date 2018/01/12. 22:31
 * @edithor
 * @date
 */
public class RemoteService extends Service {
    private static String TAG = "COCO";
    private ServiceConnection conn;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        conn = new CusServiceConnection();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "remote start");
        this.bindService(new Intent(RemoteService.this, LocalService.class), conn, Context.BIND_IMPORTANT);


        //前台服务设置
        /*PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, 0);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "1");
        builder.setTicker("service").setContentIntent(pendingIntent).setContentTitle("service keep alive").setAutoCancel(false).setContentText("content").setWhen(System.currentTimeMillis());

        startForeground(startId, builder.build());*/


        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.bindService(new Intent(RemoteService.this, LocalService.class), conn, Context.BIND_IMPORTANT);
        this.startService(new Intent(RemoteService.this, LocalService.class));
    }

    class MyBinder extends RemoteConnection.Stub {

        @Override
        public String getPackageName() throws RemoteException {
            return "RemoteService";
        }
    }

    class CusServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            Log.i(TAG, "connect with local service");
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.i(TAG, "disconnect with local service");
            RemoteService.this.bindService(new Intent(RemoteService.this, LocalService.class), conn, Context.BIND_IMPORTANT);
            RemoteService.this.startService(new Intent(RemoteService.this, LocalService.class));
        }
    }
}
